import { TOKEN_NAME } from '@/config/global';
import { authLogin, authUserInfo, authSurveyLogin } from '@/api/auth';
import { MessagePlugin } from 'tdesign-vue';

const canSurveyLogin = process.env.VUE_APP_SURVEY_ENABLE === 'true';

const InitUserInfo = {
  roles: [],
};

// 定义的state初始值
const state = {
  token: localStorage.getItem(TOKEN_NAME), // 默认token不走权限
  userInfo: InitUserInfo,
};

const mutations = {
  setToken(state, token) {
    localStorage.setItem(TOKEN_NAME, token);
    state.token = token;
  },
  removeToken(state) {
    localStorage.removeItem(TOKEN_NAME);
    localStorage.removeItem('surveyUserInfo');
    state.token = '';
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
};

const getters = {
  token: (state) => state.token,
  roles: (state) => state.userInfo?.roles,
  tenantId: (state) => state.userInfo?.tenant?.id,
  username: (state) => state.userInfo?.admin?.username,
  isSuperAdmin: (state) => state.userInfo?.isSuperAdmin,
};

const actions = {
  async login({ commit }, userInfo) {
    // const mockLogin = async (userInfo) => {
    //   登录请求流程
    //   console.log(userInfo);
    //   const { account, password } = userInfo;
    //   if (account !== 'td') {
    //     return {
    //       code: 401,
    //       message: '账号不存在',
    //     };
    //   }
    //   if (['main_', 'dev_'].indexOf(password) === -1) {
    //     return {
    //       code: 401,
    //       message: '密码错误',
    //     };
    //   }
    //   const token = {
    //     main_: 'main_token',
    //     dev_: 'dev_token',
    //   }[password];
    //   return {
    //     code: 200,
    //     message: '登陆成功',
    //     data: 'main_token',
    //   };
    // };

    // const res = await mockLogin(userInfo);
    try {
      const res = await authLogin(userInfo);

      if (res.data.code !== 200) {
        throw new Error(res?.data?.message ?? '登录失败');
      }

      commit('setToken', res.data.data);

      // 登录账号继续登录问卷账号
      if (canSurveyLogin) {
        const surRes = await authSurveyLogin(userInfo);
        const store = {
          userInfo: surRes,
          loginTime: Date.now(),
        };

        localStorage.setItem('surveyUserInfo', JSON.stringify(store));
        localStorage.setItem('survey_token', surRes?.token ?? '');
      }
    } catch (error) {
      MessagePlugin.error(error?.message ?? '登录失败');
      return Promise.reject(error);
    }
  },
  async getUserInfo({ commit, state, dispatch }) {
    // const mockRemoteUserInfo = async (token) => {
    //   if (token === 'main_token') {
    //     return {
    //       name: 'td_main',
    //       roles: ['ALL_ROUTERS'],
    //     };
    //   }
    //   return {
    //     name: 'td_dev',
    //     roles: ['UserIndex', 'DashboardBase', 'login'],
    //   };
    // };

    // const res = await mockRemoteUserInfo(state.token);

    try {
      const res = await authUserInfo();

      if (res.data.code === 200) {
        commit('setUserInfo', { ...res.data.data, roles: ['ALL_ROUTERS'] });
      } else {
        throw new Error(res?.data?.message ?? '获取用户信息失败');
      }
    } catch (error) {
      MessagePlugin.error(error?.message ?? '获取用户信息失败');
    }
  },
  async logout({ commit }) {
    commit('removeToken');
    commit('setUserInfo', InitUserInfo);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
